/**
 * 2018年12月24日上午7:00:06
 * @author 谢进财
 */
package com.baihang.project.ds.shiro;

import java.util.Collection;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.baihang.project.ds.model.EmployeeModel;

/**
 * @author whati
 *
 */
public class DsRealm extends AuthorizingRealm {
	private static Logger logger = LoggerFactory.getLogger(DsRealm.class);
	@Autowired
	private ShiroService service;
	/* (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken userToken = (UsernamePasswordToken)token;
		String userName = userToken.getUsername();		
		String password = String.valueOf(userToken.getPassword());
		EmployeeModel model = service.getEmployeeModel(userName, password);
		if(model != null) {
			User user = new User();
			user.setMenus(model.getMenus());
			user.setRealName(model.getName());
			user.setUserName(model.getUserName());
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, model.getPassword(), userName);
			if(info !=null) {
				keepOnlyOneUser(userName);
			}
			return info;
		}
		return null;
	}
	
	/**
	 * 同一帐号，只能有一个在线
	 * @param userName
	 */
	public void keepOnlyOneUser(String userName) {
		 //处理session 将同样的帐号先删除先
       DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
       DefaultWebSessionManager sessionManager = (DefaultWebSessionManager)securityManager.getSessionManager();
       Collection<Session> sessions = sessionManager.getSessionDAO().getActiveSessions();//获取当前已登录的用户session列表
       for(Session session:sessions){
           //清除该用户以前登录时保存的session
       	Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
       	if(obj!=null) {
       		SimplePrincipalCollection spc =(SimplePrincipalCollection)obj;
       		if (spc.getPrimaryPrincipal() != null) {
					User user = (User) spc.getPrimaryPrincipal();// 转成User
					if(user.getUserName().equals(userName)) {
						sessionManager.getSessionDAO().delete(session);//删除
						logger.info("{}被踢下线",userName);
					}
				}
       	}else {
       		continue;
       	}       	
       }
	}
}
